package com.shadow.demo.common.util;

import com.shadow.demo.common.constants.PunctuationConstants;
import lombok.Getter;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public final class ValidationUtils {

    @Getter
    private static final Validator validator;

    static {
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.getValidator();
    }

    private ValidationUtils() {
    }

    /**
     * 校验对象.
     * @param object        待校验对象
     * @param groups        待校验的组
     */
    public static void validateEntity(final Object object, final Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint:  constraintViolations) {
                msg.append(constraint.getMessage());
            }
            throw new RuntimeException(msg.toString());
        }
    }

    /**
     * 校验对象.
     * @param object        待校验对象
     * @param groups        待校验的组
     */
    public static String validateEntityField(final Object object, final Class<?>... groups) {
        final Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint:  constraintViolations) {
                msg.append(constraint.getMessage()).append(PunctuationConstants.SPLIT_SEMICOLON);
            }
            return  msg.toString();
        }
        return "";
    }
}
